package com.atguigu.Des;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.Base64;

/**
 * @author  微信支付团队
 * <p>
 * date : 2021-04-21
 *
 *  微信支付团队自己做的 依赖 中的类;  bouncy castle
 */
public class AesUtil {

    static final int KEY_LENGTH_BYTE = 32;
    static final int TAG_LENGTH_BIT = 128;
    private final byte[] aesKey;

    public AesUtil(byte[] key) {
        if (key.length != KEY_LENGTH_BYTE) {
            throw new IllegalArgumentException("无效的ApiV3Key，长度必须为32个字节");
        }
        this.aesKey = key;
    }

    /**
     * 用于解密
     * */
    public String decryptToString(  byte[] associatedData, byte[] nonce, String ciphertext  )
            throws GeneralSecurityException, IOException {
        try {
            //Cipher  初始化transformation(转换模式) 格式是: 算法/工作模式/填充模式(algorithm/mode/padding)     三剑客 构成一个 密码器Cipher
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");  //AEs算法/gcm工作模式/nopadding填充

            //Key key = new SecretKeySpec(aesKey, "AES");
            //SecretKeySpec key = new SecretKeySpec(aesKey, "AES");
            SecretKey  key = new SecretKeySpec(aesKey, "AES");  //密钥字节数组 转成密钥对象

            GCMParameterSpec spec = new GCMParameterSpec(TAG_LENGTH_BIT, nonce);  //初始化工作模式对象  gcm 参数指定; 使用指定的身份验证标记位长度和IV缓冲区构造GCMParameterSpec。

            cipher.init(Cipher.DECRYPT_MODE, key, spec);  // 初始化加密算法

            cipher.updateAAD(associatedData); ///??????????

            return new String(cipher.doFinal(Base64.getDecoder().decode(ciphertext)), StandardCharsets.UTF_8);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            throw new IllegalStateException(e);
        } catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
            throw new IllegalArgumentException(e);
        }
    }


    public static void main(String[] args) throws GeneralSecurityException, IOException {


    }


}
